import store from '../store'
import * as types from '../store/action_type'

const loginPermission = async function (to, from , next) {
  let res = await store.dispatch(`user/${types.USER_VALIDATE}`);
  // debugger
  let needLogin = to.matched.some(item => item.meta.needLogin);
  if(!store.state.user.hasPermission){
    if(needLogin){
      if(res){
        next();
      }else{
        next('/login')
      }
    }else {
      next()
    }
  }else{
    if(to.path === '/login'){
      next('/')
    }else{
      next()
    }
  }
  console.log(res);
  // next();
}

export const menuPermisson = async function(to, from, next) {
  if (store.state.user.hasPermission) {
    // 添加路由这里需要判断是否添加过路由了 
    if (!store.state.user.menuPermission) {
      // 添加路由完成，但是是属于异步加载，不会立即更新
      store.dispatch(`user/${types.ADD_ROUTE}`);
      //replace 相当于replaceState替换掉并不进入历史记录 把路径添加完全
      next({ ...to, replace: true }); // 如果是next()时，进入到页面时报404.
    } else {
      next();
    }
  } else {
    next();
  }
}

export const createWebSockect = function(to, from, next) {
  // 如果登陆了 但是没有创建websocket
  //store.state.ws是在src/store/rootModule.js中存值变量
  if(store.state.user.hasPermission && !store.state.ws){//调用创建ws方法
    store.dispatch(`${types.CREATE_WEBSOCKET}`);
    next();
  }else{//登录了并且创建ws
    next();
  }
}

export default {
  loginPermission,
  menuPermisson,
  createWebSockect
}